package com.example.analysis.utils;

import org.apache.commons.math3.distribution.TDistribution;

public class TTest {

    /**
     * Student's t检验（方差齐性）, t值
     */
    public static double calculateStudentsT(double[] group1, double[] group2) {
        double mean1 = ComCalcUtils.calcMean(group1), mean2 = ComCalcUtils.calcMean(group2);
        double pooledVariance = ((group1.length - 1) * ComCalcUtils.calcVariance(group1) + (group2.length - 1) * ComCalcUtils.calcVariance(group2))
                / (group1.length + group2.length - 2);
        return (mean1 - mean2) / Math.sqrt(pooledVariance * (1.0 / group1.length + 1.0 / group2.length));
    }

    /**
     * Welch's t检验（方差不齐），t值
     */
    public static double calculateWelchT(double[] group1, double[] group2) {
        double mean1 = ComCalcUtils.calcMean(group1), mean2 = ComCalcUtils.calcMean(group2);
        return (mean1 - mean2) / Math.sqrt(ComCalcUtils.calcVariance(group1) / group1.length + ComCalcUtils.calcVariance(group2) / group2.length);
    }

    /**
     * 计算Welch检验的自由度
     */
    public static double calculateWelchDF(double[] group1, double[] group2) {
        double var1 = ComCalcUtils.calcVariance(group1), var2 = ComCalcUtils.calcVariance(group2);
        double numerator = Math.pow(var1 / group1.length + var2 / group2.length, 2);
        double denominator = Math.pow(var1 / group1.length, 2) / (group1.length - 1)
                + Math.pow(var2 / group2.length, 2) / (group2.length - 1);
        return numerator / denominator;
    }

    /**
     * 计算t检验的p值（双尾） < 0.05则显著
     */
    public static double calculateTTestPValue(double tValue, double df) {
        TDistribution tDist = new TDistribution(df);
        return 2 * (1 - tDist.cumulativeProbability(Math.abs(tValue)));
    }
}
